package com.yiqi.lottery.feature.mine.view;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.suozhang.framework.component.http.ApiError;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.entity.bo.UserInfoBo;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yiqi.lottery.R;
import com.yiqi.lottery.common.alipay.PayResult;
import com.yiqi.lottery.entity.bo.PayStautsBo;
import com.yiqi.lottery.entity.bo.RechargeBo;
import com.yiqi.lottery.feature.home.view.RechrageWebActivity;
import com.yiqi.lottery.feature.mine.contract.RechargeContract;
import com.yiqi.lottery.feature.mine.dependencies.recharge.DaggerRechargeComponent;
import com.yiqi.lottery.feature.mine.dependencies.recharge.RechargePresenterModule;
import com.yiqi.lottery.feature.mine.view.adapter.RechargeMoneyAdapter;
import com.yiqi.lottery.framework.api.UserApi;
import com.yiqi.lottery.wxapi.WXPayEntryActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RechargeActivity extends BaseActivity implements RechargeContract.View, BaseQuickAdapter.OnItemClickListener, TextWatcher {


    private static final int SDK_PAY_FLAG = 1;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.rv_user_money)
    RecyclerView mRvUserMoney;
    RechargeMoneyAdapter mDateAdapter;
    @Inject
    RechargeContract.Presenter mPresenter;
    @BindView(R.id.edt_recharge_money)
    EditText mEdtRecharge_money;
    @BindView(R.id.rd_show_alipay)
    RadioButton mRdShowAlipay;
    @BindView(R.id.rd_show_wxpay)
    RadioButton mRdShowWxpay;
    @BindView(R.id.tv_user_recharge_name)
    TextView mTvUserRechargeName;
    @BindView(R.id.tv_user_recharge_balance)
    TextView mTvUserRechargeBalance;

    private int mRechargePrize;
    private int mRechargeType = 0;
    private UserInfoBo mUserInfoBo;


    private String mPayId=null;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_recharge;
    }

    @Override
    protected void initView() {
        initToolBar(mToolbar, "充值", true, true);
    }

    @Override
    protected void initInjector() {
        DaggerRechargeComponent.builder().rechargePresenterModule(new RechargePresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initData() {
        initAdapter();
        mUserInfoBo = (UserInfoBo) this.getIntent().getSerializableExtra("user");
        if (AM.user().isLogin()) {

            AM.api().createApiService(UserApi.class)
                    .getUserInfo()
                    .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                    .subscribe(new Observer<UserInfoBo>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(UserInfoBo userInfoBo) {
                    if (userInfoBo != null) {
                        mTvUserRechargeName.setText(userInfoBo.getUsername());
                        mTvUserRechargeBalance.setText("￥" + userInfoBo.getBalance_amount());
                    }
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!TextUtils.isEmpty(mPayId)) {
            mPresenter.toYLPay(mPayId);
        }
    }

    private void initAdapter() {
        mRvUserMoney.setLayoutManager(new GridLayoutManager(this, 3));
        mDateAdapter = new RechargeMoneyAdapter(getMoney());
        mRvUserMoney.setAdapter(mDateAdapter);
        mDateAdapter.setOnItemClickListener(this);

    }

    @Override
    protected void initEvent() {
        mEdtRecharge_money.addTextChangedListener(this);
        IntentFilter filter = new IntentFilter(WXPayEntryActivity.action);
        registerReceiver(broadcastReceiver, filter);
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                if (intent.getBooleanExtra("data", false)) {
                    T.showShort("充值成功！");
                    finish();
                }
            }
        }


    };

    @Override
    public void showMyRechargeSuccess(RechargeBo msg) {
        if (msg == null) return;
        if (mRechargeType == 1) {
            if (msg.getWxpay() != null)
                toWxPay(msg.getWxpay());
        } else if (mRechargeType == 2) {
            if (!TextUtils.isEmpty(msg.getAlipay()))
                toAlipay(msg);
        } else if (mRechargeType == 3) {
            getRechargeData(msg);

        }

    }



    private void getRechargeData(RechargeBo msg){

        OkHttpClient okHttpClient = new OkHttpClient();
        RechargeBo.PostDataBean bean=msg.getPost_data();
        if (msg.getPost_data()==null) return;
        mPayId=msg.getRecharge_id();
        RequestBody requestBody = new FormBody.Builder()
                .add("outOid", bean.getOutOid())
                .add("merchantCode", bean.getMerchantCode())
                .add("mgroupCode", bean.getMgroupCode())
                .add("tranAmount", bean.getTranAmount())
                .add("payType", bean.getPayType())
                .add("goodName", bean.getGoodName())
                .add("sign", bean.getSign())
                .add("notifyUrl", bean.getNotifyUrl())
                .add("pageUrl", bean.getPageUrl())
                .build();

        final Request request = new Request.Builder()
                .url(msg.getPost_url())
                .post(requestBody)//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {


            @Override
            public void onFailure(Call call, IOException e) {
             T.showShort(e.getMessage()+"");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.code()==ApiError.SUCCESS.code()){
                    String html=response.body().string();
                    Intent intent=new Intent(RechargeActivity.this,RechrageWebActivity.class);
                    intent.putExtra("recharge",html);
                    startActivity(intent);

                }

            }
        });

    }

    @Override
    public void showWithdrawSuccess(RechargeBo msg) {

    }

    @Override
    public void showYLPaySuccess(PayStautsBo msg) {
        mPresenter.doGetUserInfo();
        showMsg(msg.getStatus() == 1 ? "待支付" : msg.getStatus() == 2 ? "支付成功" : "");
    }

    @Override
    public void showUserInfoSuccess(UserInfoBo userInfoBo) {
        mTvUserRechargeName.setText(userInfoBo.getUsername());
        mTvUserRechargeBalance.setText("￥" + userInfoBo.getBalance_amount());
    }

    private void toWxPay(RechargeBo.WxPayBo wxPayBo) {
        IWXAPI api = WXAPIFactory.createWXAPI(this, wxPayBo.getAppid());
        api.registerApp(wxPayBo.getAppid());
        PayReq req = new PayReq();
        req.appId = wxPayBo.getAppid();
        req.partnerId = wxPayBo.getPartnerid();
        req.prepayId = wxPayBo.getPrepayid();
        req.nonceStr = wxPayBo.getNoncestr();
        req.timeStamp = wxPayBo.getTimestamp();
        req.packageValue = "Sign=WXPay";
        req.sign = wxPayBo.getSign();
        api.sendReq(req);
    }

    /**
     * 支付宝支付
     */
    private void toAlipay(RechargeBo msg) {
        final String orderInfo = msg.getAlipay();   // 订单信息

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(RechargeActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Logger.e("msg-------->", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        T.showShort("支付成功");
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        T.showShort("支付失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };

    @Override
    public void showMyRechargeError(String msg) {
        T.showShort("支付失败！");
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        mDateAdapter.changeState(position);
        mRechargePrize = mDateAdapter.getData().get(position);
        mEdtRecharge_money.setText(mRechargePrize + "");
    }


    @OnClick(R.id.btn_to_recharge)
    public void onViewClicked() {
        if (mRechargeType == 0) {
            T.showShort("请选择支付方式！");
            return;
        }
        if (TextUtils.isEmpty(mEdtRecharge_money.getText().toString())) {
            T.showShort("请选择支付金额");
            return;
        }

        if (mRechargePrize > 100000) {
            T.showShort("单笔充值金额不能超过十万！");
            return;
        }
        try {
            mPresenter.doRecharge(Integer.parseInt(mEdtRecharge_money.getText().toString()), mRechargeType);
        } catch (Exception e) {

        }

    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() > 0) {
            mRechargePrize = Integer.valueOf(s.toString());
            switch (mRechargePrize) {
                case 50:
                    mDateAdapter.changeState(0);
                    break;
                case 100:
                    mDateAdapter.changeState(1);
                    break;
                case 200:
                    mDateAdapter.changeState(2);
                    break;
                case 500:
                    mDateAdapter.changeState(3);
                    break;
                case 1000:
                    mDateAdapter.changeState(4);
                    break;
                case 2000:
                    mDateAdapter.changeState(5);
                    break;
                default:
                    mDateAdapter.changeNull();
                    mDateAdapter.notifyDataSetChanged();
                    if (mRechargePrize > 100000) {
                        T.showShort("单笔充值金额不能超过十万！");
                        return;
                    }
                    break;
            }
        } else {
            mDateAdapter.changeNull();
            mDateAdapter.notifyDataSetChanged();
        }
    }

    public List<Integer> getMoney() {
        List<Integer> mDateList = new ArrayList<>();
        mDateList.add(50);
        mDateList.add(100);
        mDateList.add(200);
        mDateList.add(500);
        mDateList.add(1000);
        mDateList.add(2000);
        return mDateList;

    }

    @OnClick({R.id.btn_show_alipay, R.id.btn_show_wxpay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_show_alipay:
                mRdShowAlipay.setChecked(true);
                mRdShowWxpay.setChecked(false);
                mRechargeType = 2;
                break;
            case R.id.btn_show_wxpay:
                mRdShowAlipay.setChecked(false);
                mRdShowWxpay.setChecked(true);
                mRechargeType = 1;
                break;
        }
    }


    @OnClick(R.id.btn_pay_yl)
    public void onViewYLClicked() {
        mRechargeType = 3;
        onViewClicked();
    }
}